package com.huizhonglm.diap.ui.app;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.bruce.common.utils.EmptyUtil;
import com.huizhonglm.diap.R;
import com.huizhonglm.diap.api.API;
import com.huizhonglm.diap.api.HttpCallback;
import com.huizhonglm.diap.api.Status;
import com.huizhonglm.diap.api.model.app.CheckUpdateResponse;
import com.huizhonglm.diap.api.model.user.ClaimShopParams;
import com.huizhonglm.diap.api.model.user.ClaimShopResponse;
import com.huizhonglm.diap.api.model.user.ReferrerParams;
import com.huizhonglm.diap.api.model.user.ReferrerResponse;
import com.huizhonglm.diap.core.config.Constants;
import com.huizhonglm.diap.core.location.LocationService;
import com.huizhonglm.diap.core.location.LocationUtil;
import com.huizhonglm.diap.core.storage.model.LocationInfo;
import com.huizhonglm.diap.core.storage.pref.Keys;
import com.huizhonglm.diap.core.storage.pref.Preferences;
import com.huizhonglm.diap.core.upgrade.Upgrade;
import com.huizhonglm.diap.core.utils.DialogUtil;
import com.huizhonglm.diap.core.utils.LogUtil;
import com.huizhonglm.diap.core.utils.ToastUtil;
import com.huizhonglm.diap.core.utils.UserUtil;
import com.huizhonglm.diap.presenters.app.CheckUpdatePersenter;
import com.huizhonglm.diap.ui.BaseActivity;
import com.huizhonglm.diap.ui.app.iView.CheckUpdateIView;
import com.huizhonglm.diap.ui.tab.TabhostActivity;

/**
 * 启动页
 *
 * @author LiXiaoLong
 * @version 1.0
 * @since 2016-03-01 17:40
 */
public class StartupActivity extends BaseActivity implements CheckUpdateIView {

    private View proBar;

    private CheckUpdatePersenter cuPersenter;

    private boolean isCheckedUpdate = false;
    private boolean isCheckedLocation = false;
    private boolean needToLogin = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_startup);
        registerStartupReceiver();
        cuPersenter = new CheckUpdatePersenter(this);
        assignViews();

        Intent intent = getIntent();
        String scheme = intent.getScheme();
        Uri uri = intent.getData();
        LogUtil.print("StartupActivity - scheme:"+scheme);
        if (uri != null) {
            String host = uri.getHost();
            LogUtil.print("StartupActivity - host:"+host);
            String shopId = uri.getQueryParameter("shopId");
            String referrerId = uri.getQueryParameter("referrerId");
            if (!TextUtils.isEmpty(shopId) && TextUtils.isEmpty(referrerId)) {
                LogUtil.print("StartupActivity - shopId:"+shopId);
                if (UserUtil.isLogin()) {
                    claimShop(shopId);
                } else {
                    Preferences.getInstance().edit().putBoolean(Keys.needToLogin, true).apply();
                }
            } else if (TextUtils.isEmpty(shopId) && !TextUtils.isEmpty(referrerId)) {
                LogUtil.print("StartupActivity - referrerId:"+referrerId);
                if (UserUtil.isLogin()) {
                    addReferrer(referrerId);
                } else {
                    Preferences.getInstance().edit().putBoolean(Keys.needToLogin, true).apply();
                }
            }
        }
    }

    @Override
    protected void assignViews() {
        proBar = findViewById(R.id.location_pro);
        cuPersenter.checkUpdate();
        checkLoaction();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(startupReceiver);
    }

    @Override
    public void onCheckVersionSuccess(CheckUpdateResponse resp) {
        if (resp != null && !"0".equals(resp.getMode())) {
            showUpdateDialog(resp);
        } else {
            isCheckedUpdate = true;
            enterHome();
        }
    }

    @Override
    public void onCheckVersionFailure() {
        isCheckedUpdate = true;
        ToastUtil.makeTextShort("检测新版本失败，请稍后重试");
        enterHome();
    }

    private void showUpdateDialog(final CheckUpdateResponse resp){
        proBar.setVisibility(View.GONE);
        DialogUtil.showNormalDialog(this, "已有新版本" + resp.getVersion(), resp.getDesc(), "暂不更新", "立即更新", new DialogUtil.OnDialogBtnClickListener() {
            @Override
            public void onBtnClick(String btnText) {
                isCheckedUpdate = true;
                if ("立即更新".equals(btnText)) {
                    if (!EmptyUtil.isEmpty(resp.getApkUrl())) {
                        Upgrade.doUpgrade(StartupActivity.this, resp.getMode(), resp.getApkUrl(), resp.getVersion());
                    } else {
                        ToastUtil.makeTextShort("更新地址有误");
                    }
                    if ("1".equals(resp.getMode())) {// 提示更新
                        enterHome();
                    } else {// 强制更新
                        proBar.setVisibility(View.VISIBLE);
                    }
                } else {
                    if ("1".equals(resp.getMode())) {// 提示更新
                        enterHome();
                    } else {// 强制更新
                        finish();
                    }
                }
            }
        });
    }

    private void checkLoaction(){
        LocationInfo locInfo = LocationUtil.getLocation();
        if (locInfo != null) {
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    isCheckedLocation = true;
                    enterHome();
                }
            }, 1000);
        } else {
            startService(new Intent(this, LocationService.class));
        }
    }

    private void enterHome(){
        if (isCheckedUpdate && isCheckedLocation) {
            if (Preferences.getInstance().getBoolean(Keys.isGuided, false)) {
                startActivity(new Intent(StartupActivity.this, TabhostActivity.class));
            } else {
                Preferences.getInstance().putBoolean(Keys.isGuided, true);
                startActivity(new Intent(StartupActivity.this, GuideActivity.class));
            }
            finish();
        }
    }

    private void registerStartupReceiver(){
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constants.LOCATE_SERVICE_COMPLATE_ACTION);
        filter.addAction(Constants.HUIZHONGLM_EXIT_ACITON);
        filter.setPriority(Integer.MAX_VALUE);
        registerReceiver(startupReceiver, filter);
    }

    private BroadcastReceiver startupReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            isCheckedLocation = true;
            if (intent.getAction().equals(Constants.LOCATE_SERVICE_COMPLATE_ACTION)) {
                LocationInfo locInfo = (LocationInfo) intent.getSerializableExtra(Constants.LOCATE_SERVICE_LOCATION);
                if (locInfo != null) {
                    LogUtil.print("locationService - startup >>> receiver - lng=" + locInfo.getLongitude() + "-lat=" + locInfo.getLatitude());
                } else {
                    LogUtil.print("locationService - startup >>> receiver - failured");
                }
                enterHome();
            }

            if (Constants.HUIZHONGLM_EXIT_ACITON.equals(intent.getAction())) {
                finish();
            }
        }
    };


    public void claimShop(final String shopId) {
        ClaimShopParams params = new ClaimShopParams(API.buildUri(API.CLAIM_SHOP));
        params.userId = UserUtil.getUserId();
        params.shopId = shopId;
        API.http().post("claimShop", params, new HttpCallback() {
            @Override
            public void onSuccess(String result) {
                if (!EmptyUtil.isEmpty(result)) {
                    ClaimShopResponse resp = JSON.parseObject(result, ClaimShopResponse.class);
                    if (resp == null || Status.FAILURE.equals(resp.getStatus())) {
                        ToastUtil.makeTextShort("扫描二维码认领商铺失败");
                    }
                } else {
                    ToastUtil.makeTextShort("扫描二维码认领商铺失败");
                }
            }

            @Override
            public void onFailure(Throwable ex) {
                ToastUtil.makeTextShort("扫描二维码认领商铺失败");
            }
        });
    }

    public void addReferrer(final String referrerId) {
        ReferrerParams params = new ReferrerParams(API.buildUri(API.REFERRER_ADD));
        params.userId = UserUtil.getUserId();
        params.referrerId = referrerId;
        API.http().post("addReferrer", params, new HttpCallback() {
            @Override
            public void onSuccess(String result) {
                if (!EmptyUtil.isEmpty(result)) {
                    ReferrerResponse resp = JSON.parseObject(result, ReferrerResponse.class);
                    if (resp == null) {
                        ToastUtil.makeTextShort("扫描二维码添加推荐人失败");
                    }
                } else {
                    ToastUtil.makeTextShort("扫描二维码添加推荐人失败");
                }
            }

            @Override
            public void onFailure(Throwable ex) {
                ToastUtil.makeTextShort("扫描二维码添加推荐人失败");
            }
        });
    }
}
